package org.stayfool.mqtt.test;

import io.netty.buffer.ByteBuf;
import io.netty.handler.codec.mqtt.MqttPublishMessage;
import io.netty.handler.codec.mqtt.MqttQoS;
import io.netty.util.CharsetUtil;
import org.apache.commons.codec.digest.DigestUtils;
import org.junit.Test;
import org.stayfool.client.MqttClient;
import org.stayfool.client.MqttOption;
import org.stayfool.client.event.EventType;

/**
 * Created by stayfool on 2016/12/7.
 */
public class DeviceSimulate {

    //d:{userId}:{productId}:{deviceType}:{sn}:{deviceId}
    private String clientId = "d:1:1:wifi:00001:351530415846068224";

    private String deviceId = "351530415846068224";

    private String token = "M_6%2$_MX$2#20##Y0MQ6%&X%X&X%%I#";

    //timestamp
    private String username = String.valueOf(System.currentTimeMillis());
    //signature
    private String password = DigestUtils.md5Hex(deviceId + username + token);

    private String topic = "data/" + deviceId + "/wifistatus";

    private String cmd = "cmd/" + deviceId;

    @Test
    public void simulate() throws InterruptedException {
//        System.setProperty("javax.net.debug", "all");

        MqttOption option = MqttOption.instance()
                .clientId(clientId)
                .port(1883).host("localhost")
//                .loglevel("debug")
//                .port(8883).host("localhost")
//                .keyPass("keyPassword").keyPath("nettyserver.jks")
                .username(username).password(password);
        MqttClient client = new MqttClient(option);

        client.addCallback(EventType.MESSAGE_ARRIVE, (msg) -> {
            ByteBuf b = ((MqttPublishMessage) msg).payload();
            System.out.println(b.toString(CharsetUtil.UTF_8));
        });

        client.connect().sync();

        if (client.isConnect()) {

            client.subscribe(cmd, MqttQoS.AT_LEAST_ONCE);

            while (true) {
                client.publish(topic, MqttQoS.AT_LEAST_ONCE, false, "{\"id\":\"client connect\",\"content\":\"I am in!\"}");
                Thread.sleep(2000);
            }
        }
    }
}
